<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\madmin\service;


use app\index\model\LotteryLogistics;
use app\madmin\model\Commodity;
use app\madmin\model\Coupon;
use app\madmin\model\LotteryConfig;
use app\madmin\model\LotteryLog;
use app\madmin\model\LotteryPrize;
use app\madmin\model\Sku;
use app\utils\Addons;
use think\Exception;

class LotteryService
{
    protected $user;

    protected $style = [];
    protected $name = [1 => '九宫格',2 => '刮刮乐'];
    public function __construct(){
        global $user;
        $this->user = $user;
        $style = [17 => 1,18 => 2];
//        $this->style = [1,2];
        foreach ($style AS $key => $value)
            $this->style[]  = Addons::check($this->user['mall_id'], $key) ? $value : 0;
    }

    /**
     * 配置详情
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function config_read(int $id){
        $find = LotteryConfig::find($id)->toArray();
        foreach ($find['config'] AS $key => $value){
            if ($value['type'] != 4)continue;
            $find['config'][$key]['limit'] = $value['limit'] - LotteryPrize::where('uniqid',$value['uniqid'])->value('number');
        }
        return [HTTP_SUCCESS,$find];
    }

    /**
     * 抽奖配置列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function config_list(array $data,int $page, int $size){
        if (!in_array($data['style'],$this->style))
            throw new Exception($this->name[$data['style']].'未开启',HTTP_NOTACCEPT);
        $where[] = ['mall_id','=',$this->user->mall_id];
        if (!empty($data['start_time']))$where[] = ['create_time','>',$data['start_time']];
        if (!empty($data['end_time']))$where[] = ['create_time','>',$data['end_time']];
        if (!empty($data['style']))$where[] = ['style','=',$data['style']];
        $list = LotteryConfig::where($where)
            ->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS,$list];
    }

    /**
     * 添加抽奖配置
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function config_save(array $data){
        if (!in_array($data['style'],$this->style))
            throw new Exception($this->name[$data['style']].'未开启',HTTP_NOTACCEPT);
        $data['mall_id'] = $this->user->mall_id;
        $data['status'] = 0;
        $data['config'] = $this->get_config_data($data['config']);
        $data = LotteryConfig::create($data);
        return [HTTP_SUCCESS,$data];
    }

    /**
     * 修改抽奖配置
     * @param int $id
     * @param array $data
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function config_update(int $id, array $data){
        if (empty($data['style']))unset($data['style']);
        $config = LotteryConfig::find($id);
        if (empty($config))
            throw new Exception('配置不存在',HTTP_NOTACCEPT);
        if ($config->status == 1)
            throw new Exception('请先关闭抽奖再修改',HTTP_NOTACCEPT);
        $data['status'] = 0;
        $data['config'] = $this->get_config_data($data['config']);
        $config = $config->save($data);
        return [HTTP_SUCCESS,$config];
    }

    /**
     * 抽奖配置数据处理
     * @param string $config
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function get_config_data(array $config) : string{
        $probability = array_column($config,'probability');
        if (100 <> array_sum($probability))
            throw new Exception('所有奖品概率相加必须等于100%',HTTP_NOTACCEPT);
        foreach ($config AS $key => $value) {
            if ($value['type'] != 1)
                $config[$key]['uniqid'] = md5(uniqid() . rand(1000, 9999) . $key);
            else
                $config[$key]['uniqid'] = '000000';
            if ($value['type'] == 4){
                if (!empty($value['value']['commodity_id'])){
                    $commodity = Commodity::field('name,master')
                        ->where('id',$value['value']['commodity_id'])
                        ->find();
                    if (empty($commodity))
                        throw new Exception('商品不存在',HTTP_NOTACCEPT);
                    $config[$key]['value']['name'] = $commodity->name;
                    $config[$key]['value']['master'] = $commodity->master;
                    if (!empty($value['value']['sku_id'])){
                        $sku = Sku::where('id',$value['value']['sku_id'])->value('pvs_value');
                        if (empty($sku))
                            throw new Exception('商品规格不存在',HTTP_NOTACCEPT);
                        $config[$key]['value']['pvs_value'] = $sku;
                    }
                }else{
                    throw new Exception('商品未上传',HTTP_NOTACCEPT);
                }
            }elseif($value['type'] == 5){
                if (!empty($value['value']['coupon_id'])) {
                    $coupon = Coupon::where('id',$value['value']['coupon_id'])
                        ->find();
                    if (empty($coupon))
                        throw new Exception('优惠券不存在',HTTP_NOTACCEPT);
                    $config[$key]['value']['name'] = $coupon->name;
                }else{
                    throw new Exception('优惠券未选择',HTTP_NOTACCEPT);
                }
            }
        }
        return json_encode($config);
    }

    /**
     * 删除配置处理
     * @param int $id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function config_delete(int $id){
        $config = LotteryConfig::find($id);
        if (empty($config))
            throw new Exception('配置不存在',HTTP_NOTACCEPT);
        $config = $config->delete();
        return [HTTP_SUCCESS,$config];
    }

    /**
     * 开启抽奖配置
     * @param int $id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function config_open(int $id,int $status){
        $config = LotteryConfig::find($id);
        if (empty($config->id))
            throw new Exception('配置不存在',HTTP_NOTACCEPT);
        if ($status == 1)
            LotteryConfig::where('mall_id',$this->user->mall_id)
                ->where('style',$config->style)
                ->update(['status' => 0]);
        $config->save(['status' => $status,'update_time' => date('Y-m-d H:i:s')]);
        return [HTTP_SUCCESS,true];
    }
    /**
     * 用户抽奖记录列表
     * @param int $id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lottery_log_list(int $page,int $size,array $data){
        $where[] = ['mall_id','=',$this->user->mall_id];
        !empty($data['type']) && $where[] = ['type','=',$data['type']];
        !empty($data['style']) && $where[] = ['style','=',$data['style']];
        !empty($data['receive']) && $where[] = ['receive','=',$data['receive']];
        $list = LotteryLog::where('mall_id',$this->user['mall_id'])
            ->with(['User','Prize','Logistics'])
            ->where('type','>',1)
            ->where($where)
            ->order('create_time DESC')
            ->paginate(['page' => $page,'list_rows' => $size]);
        return [HTTP_SUCCESS,$list];
    }

    /**
     * 用户抽奖记录详情
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lottery_log_read(int $id){
        $find = LotteryLog::with(['User','Prize','Logistics'])->find($id);
        return [HTTP_SUCCESS,$find];
    }

    /**
     * 用户奖品收货
     * @param array $ids
     * @return array
     */
    public function lottery_goods_receiving(array $ids){
        LotteryLogistics::where('lottery_log_id','IN',$ids)
            ->update(['status' => 3]);
        return [HTTP_SUCCESS,'成功'];
    }

    /**
     * 用户奖品发货
     * @param array $ids
     * @return array
     */
    public function lottery_goods_deliver(int $id,string $express_code,string $logistics){
        LotteryLogistics::where('lottery_log_id','=',$id)
            ->update(['status' => 2,'express_code' => $express_code,'logistics' => $logistics]);
        return [HTTP_SUCCESS,'成功'];
    }

}